package com.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author linyu.dai
 * @project rpc
 * @description 建造者工具
 * @creat 2022/12/18 15:56:57
 */
public class Builder<T> {

    private final Supplier<T> constructor;

    //private final List<Consumer<T>> dInject = new ArrayList<>();
    //
    //private final List<Predicate<T>> dTest = new ArrayList<>();

    //使用函数式优化 转化为链式调用
    private Consumer<T> consumerHead = t -> {};

    private Predicate<T> predicateHead = t -> true;

    private Builder(Supplier<T> constructor){
        this.constructor = constructor;
    }

    public static <T> Builder<T> getBuilder(Supplier<T> constructor){
        return new Builder<>(constructor);
    }

    public Builder<T> check(Predicate<T> predicate){
        //dTest.add(predicate);
        predicateHead =  predicateHead.and(predicate);
        return this;
    }

    public <P1> Builder<T> with(Builder.DInjectConsumer1<T,P1> consumer, P1 p1){
        Consumer<T> c = instance -> consumer.accept(instance,p1);
        //dInject.add(c);
        consumerHead = consumerHead.andThen(c);
        return this;
    }

    public <P1,P2> Builder<T> with(Builder.DInjectConsumer2<T,P1,P2> consumer, P1 p1, P2 p2){
        Consumer<T> c = instance -> consumer.accept(instance,p1,p2);
        //dInject.add(c);
        consumerHead =  consumerHead.andThen(c);
        return this;
    }

    public T build(){
        //调用构造器方法
        //调用传入的setter方法 完成属性初始话
        T instance = constructor.get();
        //dInject.forEach(dInject -> dInject.accept(instance));
        //dTest.forEach(dTest-> {
        //    if(!dTest.test(instance)){
        //        throw new RuntimeException("对象不符合规则");
        //    }
        //});
        consumerHead.accept(instance);
        boolean test = predicateHead.test(instance);
        if(!test){
            throw new RuntimeException("构建对象不符合规则");
        }
        return instance;
    }

    @FunctionalInterface
    public interface DInjectConsumer1<T,P1>{
        void accept(T t,P1 p1);
    }

    @FunctionalInterface
    public interface DInjectConsumer2<T,P1,P2>{
        void accept(T t,P1 p1,P2 p2);
    }
}
